package com.mjlf.shiro.sha;

import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.DefaultHashService;
import org.apache.shiro.crypto.hash.HashRequest;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.SimpleByteSource;
import org.junit.Test;

/**
 * @ClassName HashService
 * @auther mjlf
 * @Date 2019/6/11 9:59
 * @Description 加密服务
 */
public class HashService {

    private static final DefaultHashService defaultHashService;
    static {
        defaultHashService = new DefaultHashService();

        //加密算法名称
        defaultHashService.setHashAlgorithmName("MD5");

        //私有盐
        defaultHashService.setPrivateSalt(new SimpleByteSource("viewro"));

        //是否生成公盐， 默认false
        defaultHashService.setGeneratePublicSalt(true);

        //用于生成公盐，
        defaultHashService.setRandomNumberGenerator(new SecureRandomNumberGenerator());

        //加密迭代次数
        defaultHashService.setHashIterations(1);
    }

    public static String hash(String source, String salt){
       return hashByArg("MD5", source, salt);
    }

    /**
     * 加密方法
     * @param argName 加密算法名称， MD5, SHA-256, SHA-512等
     * @param source 加密数据源
     * @param salt 公有加密盐
     * @return
     */
    public static String hashByArg(String argName, String source, String salt){
        HashRequest request = new HashRequest
                .Builder()
                .setAlgorithmName(argName)
                .setSource(ByteSource.Util.bytes(source))
                .setSalt(salt)
                .setIterations(1)
                .build();
        String result = defaultHashService.computeHash(request).toString();
        return result;
    }
}
